package com.wanjia.estate.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSON;
import com.wanjia.estate.exception.ControllerException;
import com.wanjia.estate.pojo.print.PrintInfo;
import com.wanjia.estate.properties.PrintInfoProperties;
import com.wanjia.estate.utils.ArgumentUtil;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

@Service
@Slf4j
public class PrintInfoService {

    @Setter(onMethod_ = @Autowired)
    private PrintInfoProperties properties;

    public PrintInfo.Response info() {
        File jsonFile = null;
        try {
            // 临时json定位与父目录创建
            jsonFile = File.createTempFile("estate-PrintInfo-", ".json");

            // 查询参数构建
            PrintInfo.Request request = new PrintInfo.Request();
            request.setIp(properties.getIp());
            request.setName(properties.getName());
            request.setJson(jsonFile.getAbsolutePath());

            // 调用外部程序
            List<String> command = CollUtil.newArrayList(properties.getProgram());
            ArgumentUtil.appendArgument(request, command);
            log.debug("execute command: {}", command);
            Process process = new ProcessBuilder()
                    .command(command)
                    .redirectErrorStream(true)
                    .start();

            // 读取输出
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    log.debug("execute command output: {}", line);
                }
            }

            // 等待程序执行
            Thread.sleep(1000);

            // 文件内容解析
            if (!jsonFile.exists() || jsonFile.length() <= 0) {
                throw new NullPointerException("输出文件为空");
            }
            String jsonStr = FileUtil.readUtf8String(jsonFile);
            PrintInfo.Response response = JSON.parseObject(jsonStr, PrintInfo.Response.class);
            log.debug("execute response: {}", response);

            return response;
        } catch (IOException e) {
            throw new ControllerException("打印机状态查询异常", e);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new ControllerException("等待意外中断", e);
        } finally {
            if (jsonFile != null && jsonFile.exists()) {
                if (!FileUtil.del(jsonFile)) {
                    log.warn("临时文件删除失败: {}", jsonFile);
                }
            }
        }
    }
}
